<template>
  <div class="app-container">
    <div style="margin-bottom: 20px">
      <el-input
        v-model="queryParams.searchText"
        placeholder="请输入文件名称"
        :prefix-icon="Search"
        clearable
        style="width: 240px; margin: 0 10px"
        @keyup.enter="handleQuery"
      />
    </div>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Upload" @click="handleImport">导入</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 表格数据 -->
    <el-table v-loading="loading" :data="tableList" @selection-change="handleSelectionChange">
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <el-table-column label="文件名称" prop="name" />
      <el-table-column label="上传时间" prop="createTime" :show-overflow-tooltip="true">
        <template #default="scope">
          <span>{{ dayjs(scope.row.createTime).format("YYYY-MM-DD HH:mm:ss") }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" prop="updateTime" :show-overflow-tooltip="true">
        <template #default="scope">
          <span>{{ dayjs(scope.row.updateTime).format("YYYY-MM-DD HH:mm:ss") }}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="上传人" prop="roleKey" :show-overflow-tooltip="true" /> -->
      <el-table-column label="数据总量" prop="dataAmount" />
      <!-- <el-table-column label="呼叫时间" align="center" sortable /> -->
      <!-- <el-table-column label="通话时长" align="center" prop="createTime" sortable /> -->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-tooltip content="查看详情" placement="top">
            <el-button
              link
              type="primary"
              icon="Grid"
              @click="onViewDetailHandle(scope.row)"
              v-hasPermi="['system:role:edit']"
            ></el-button>
          </el-tooltip>

          <el-tooltip content="删除" placement="top">
            <el-button
              link
              type="primary"
              icon="Delete"
              @click="onDeleteHandle(scope.row)"
              v-hasPermi="['system:role:remove']"
            ></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" v-model="upload.open" width="400px" append-to-body>
      <el-upload
        ref="uploadRef"
        :limit="1"
        accept=".xlsx, .xls, .pdf"
        :action="upload.url"
        :headers="upload.headers"
        :data="{ data: JSON.stringify(upload.data) }"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :before-upload="handleFileBeforeUpload"
        :auto-upload="false"
        drag
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip text-center">
            <div class="el-upload__tip">
              <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的用户数据
            </div>
            <span>仅允许导入xls、xlsx、pdf格式文件。</span>
          </div>
        </template>
      </el-upload>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="upload.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 显示详情对话框 -->
    <el-dialog :title="dialogTitle" v-model="visiable" width="1000px" append-to-body>
      <ul>
        <li v-for="(item,index) in detailList" :key="index" :class="index % 2 == 0 ? 'style1' : 'style2'">
          <p>{{ item }}</p>
        </li>
      </ul>
      <!-- <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">确 定</el-button>
          <el-button @click="visiable = false">取 消</el-button>
        </div>
      </template> -->
    </el-dialog>
  </div>
</template>

<script setup name="knowledgeBase">
import { getToken } from "@/utils/auth"
import { ElMessageBox } from "element-plus"
import { Search } from "@element-plus/icons-vue"
import { delRole, listRole } from "@/api/system/role"

import { dayjs } from "element-plus"
import {
  getFastGPTDatasetListAPI,
  getFastGPTCollectionListAPI,
  deleteAPI,
  getCollectionDetailAPI,
  getDatasetDetailAPI,
  getCollectionDataListAPI,
} from "@/api/fastGPT/dataset"

const router = useRouter()
const { proxy } = getCurrentInstance()
const { sys_normal_disable } = proxy.useDict("sys_normal_disable")
/*** 用户导入参数 */
const upload = reactive({
  // 是否显示弹出层（用户导入）
  open: false,
  // 弹出层标题（用户导入）
  title: "",
  // 是否禁用上传
  isUploading: false,
  // 是否更新已经存在的用户数据
  updateSupport: 0,
  // 设置上传的请求头部
  headers: { Authorization: "Bearer " + import.meta.env.VITE_APP_FASTGPT_API_KEY_BASE },
  // 上传的地址
  url: import.meta.env.VITE_APP_FASTGPT_BASE_API + "/core/dataset/collection/create/localFile",
  data: {
    datasetId: import.meta.env.VITE_APP_FASTGPT_DATASET,
    parentId: null,
    trainingType: "chunk",
    chunkSize: 512,
    chunkSplitter: "",
    qaPrompt: "",
    metadata: {},
  },
})

const tableList = ref([])
const loading = ref(false)
const total = ref(0)
const visiable = ref(false)
const dialogTitle = ref()
const detailList = ref([])
const dateRange = ref([])

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    searchText: "",
  },
})

const { queryParams } = toRefs(data)
// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.tenantId)
  single.value = selection.length != 1
  multiple.value = !selection.length
}
/** 导入按钮操作 */
function handleImport() {
  upload.title = "用户导入"
  upload.open = true
}

/**文件改变 */
const handleFileBeforeUpload = async (rawFile, v2, v3) => {
  // 对文件名进行编码，这里以 Base64 为例
  // const encodedName = window.btoa(file.name)
  // // 重新设置文件对象的 name 属性
  // file.name = encodedName
  const newFile = new File([rawFile], encodeURIComponent(rawFile.name), { type: rawFile.type })
  return Promise.resolve(newFile)
}

/**文件上传中处理 */
const handleFileUploadProgress = (event, file, fileList) => {
  upload.isUploading = true
}

/** 文件上传成功处理 */
const handleFileSuccess = (response, file, fileList) => {
  console.log(proxy.$refs["uploadRef"], 11111111111111111111)

  file.name = encodeURIComponent(file.name)
  upload.open = false
  upload.isUploading = false
  proxy.$refs["uploadRef"].handleRemove(file)
  console.log(response, "-----------")
  if (response.code == 200) {
    proxy.$alert(
      "<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'> " +
        "操作成功" +
        "</div>",
      "导入结果",
      { dangerouslyUseHTMLString: true }
    )
    getList()
  }
}

/** 查询集合列表 */
function getList() {
  loading.value = true

  // getFastGPTDatasetListAPI({
  //   parentId: "",
  // }).then((response) => {
  //   console.log(response, "======================1")
  // })
  getFastGPTCollectionListAPI({
    pageNum: 1,
    pageSize: 10,
    datasetId: import.meta.env.VITE_APP_FASTGPT_DATASET,
    parentId: null,
    searchText: queryParams.value.searchText,
  }).then((response) => {
    tableList.value = response.data.data.map((item) => ({
      ...item,
      name: decodeURIComponent(item.name),
    }))
    total.value = response.total
    loading.value = false
    console.log(response, "======================2")
  })
}

/** 提交上传文件 */
function submitFileForm() {
  proxy.$refs["uploadRef"].submit()
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 查看详情按钮操作 */
function onViewDetailHandle(row) {
  visiable.value = true
  dialogTitle.value = row.name
  getCollectionDataListAPI({
    offset: 0,
    pageSize: 10,
    collectionId: row._id,
    searchText: "",
  }).then((res) => {
    detailList.value = res.data.list.map(obj=>{
      return obj.q
    })
    console.log(detailList.value , 111111111111);
    
    // return getDatasetDetailAPI({ id: row._id })
  })
  // getCollectionDetailAPI({ id: row._id })
  //   .then((res) => {
  //     console.log(res, "----------res")

  //     const file = new FileReader(res.data.file)
  //     console.log(file, "----------file", res.data.file)

  //     // return getDatasetDetailAPI({ id: res.data.dataset._id })
  //     // return getDatasetDetailAPI({ id: row._id })
  //   })
  //   .then((r) => {
  //     console.log(r, "----------res-2")
  //   })
}

/** 删除按钮操作 */
function onDeleteHandle(row) {
  ElMessageBox.confirm("确定要删除这条数据吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      deleteAPI({
        id: row._id,
      })
        .then(() => {
          getList()
          proxy.$modal.msgSuccess("删除成功")
        })
        .catch(() => {})
    })
    .catch(() => {})
}

getList()
// onActivated(() => {
//   getList()
// })
</script>

<style scoped lang="scss">
.style1{
  border: 1px solid #ccc;
  background-color: #f0f4ff;
  margin: 5px 0;
  padding: 8px;
  border-radius: 10px;
}
.style2{
  border: 1px solid #ccc;
  background-color: #f7f8fa;
  margin: 5px 0;
  padding: 8px;
  border-radius: 10px;
}
</style>
